package com.example.demo.service.impl;

import com.example.demo.common.CommonResult;
import com.example.demo.entity.FileVO;
import com.example.demo.repository.FileRepository;
import com.example.demo.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件接口
 *
 * @author 黄泽涛
 * @date 2021/12/30 16:20
 * @
 **/

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private FileRepository fileRepository;

    @Value("${file.upLoadFilePath}")
    private String upLoadFilePath;

    @Override
    @Transactional
    public CommonResult fileUpload(MultipartFile multipartFile) {
        FileVO fileVo = new FileVO();
//        if (multipartFile.isEmpty()) {
//            return CommonResult.failed("传入文件对象不能为空");
//        }
        //文件大小
        long fileSize = multipartFile.getSize();
        //原始文件名
        String oldFileName = multipartFile.getOriginalFilename();
        //文件UUID
        String fileName = UUID.randomUUID().toString();
        //文件类型
        String fileType = multipartFile.getContentType();
        //创建时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateTime = dateFormat.format(date);
        //判断文件夹是否存在,不存在则创建
        File file = new File(upLoadFilePath + "\\" + dateTime);
        if (!file.exists())//文件夹不存在就创建
        {
            file.mkdirs();
        }
        //获取文件后缀
        String subffix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1, oldFileName.length());
        //文件保存目录地址
        String filePath = file + "\\" + fileName + "." + subffix;
        //保存文件
        try {
            multipartFile.transferTo(new File(filePath));
            fileVo.setOldFileName(oldFileName);
            fileVo.setFileType(fileType);
            fileVo.setFileSize(fileSize);
            fileVo.setCreateTime(dateTime);
            fileVo.setFileUUID(fileName);
            fileVo.setFilePath(filePath);
            FileVO save = fileRepository.save(fileVo);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("保存文件失败");
        }
        return CommonResult.success("成功", "成功");
    }


    @Override
    public CommonResult fileDownLoad(String fileName, HttpServletResponse response) {
        FileVO fileVO = fileRepository.findByFileUUID(fileName);
        String filePath = fileVO.getFilePath();
        File file = new File(filePath);
        if (!file.exists()) {
            return CommonResult.failed("下载文件不存在");
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileVO.getOldFileName());
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            return CommonResult.failed(401, "下载文件出现异常");
        }
        return CommonResult.success("", "正在下载");
    }

    @Override
    public CommonResult getFileInformation(String fileName) {
        FileVO fileVO = fileRepository.findByFileUUID(fileName);
        if(fileVO != null){
            return CommonResult.success(fileVO, "查询成功");
        }else{
            return CommonResult.failed( "查询失败");
        }

    }
}
